from turbogears import expose, identity, validate, validators, redirect
from onlineapidoc.model import User, Template
from cherrypy import request

class TemplateController(identity.SecureResource):
    require = identity.has_any_permission("root", "tmpl-edit")
    
    @expose()
    def default(self, *args, **kwargs):
        parts = request.path.rsplit('/')
        if len(parts) == 3 and parts[-1].isdigit():
            return self.edit_template(parts[-1])


    @expose(template="onlineapidoc.templates.template.index")
    def index(self):
        templates = Template.select(orderBy='name')

        return dict(active_section='template',
                    templates=templates,
                    current_template=None)
    
    
    @expose()
    def new_template(self, name, edit_template, view_template, description):
        author = User.get(identity.current.user.id)
        Template(name=name,
                 description=description,
                 edit_template=edit_template,
                 view_template=view_template,
                 author=author)

        raise redirect('/template')

    @expose(template="onlineapidoc.templates.template.index")
    def edit_template(self, template_id):
        templates = Template.select(orderBy='name')
        current_template = Template.get(template_id)

        return dict(active_section='template',
                    templates=templates,
                    current_template=current_template)

    @expose()
    def edit_template_commit(self, template_id, name, edit_template, view_template, description):
        template = Template.get(template_id)
        template.set(name=name,
                     description=description,
                     edit_template=edit_template,
                     view_template=view_template)

        raise redirect('/template')
    
    @expose()
    def duplicate_template(self, template_id):
        template = Template.get(template_id)
        
        new_template = Template(name=template.name+_("_copy"),
                            description=template.description,
                            edit_template=template.edit_template,
                            view_template=template.view_template,
                            author=template.author)
        raise redirect('/template')
